package io.kiki.sba.registry.server.clientInterface.converter.pb;

import io.kiki.sba.registry.common.model.client.pb.MetaService;
import io.kiki.sba.registry.common.model.client.pb.StringList;
import io.kiki.sba.registry.core.model.AppRevisionInterface;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;


public class MetaServiceConvertor {

    public static MetaService convert2Pb(AppRevisionInterface service) {

        MetaService.Builder serviceBuilder = MetaService.newBuilder();
        serviceBuilder.setId(service.getId());

        for (Entry<String, List<String>> entry : Optional.ofNullable(service.getServiceParams()).orElse(new HashMap<>()).entrySet()) {
            StringList.Builder listBuilder = StringList.newBuilder().addAllValues(entry.getValue());
            serviceBuilder.putParams(entry.getKey(), listBuilder.build());
        }

        return serviceBuilder.build();
    }

    public static AppRevisionInterface convert2Java(MetaService metaService) {
        AppRevisionInterface appRevisionInterface = new AppRevisionInterface();
        appRevisionInterface.setId(metaService.getId());
        Map<String, List<String>> serviceParams = new HashMap<>();
        for (Entry<String, StringList> paramEntry : Optional.ofNullable(metaService.getParamsMap()).orElse(new HashMap<>()).entrySet()) {
            StringList value = paramEntry.getValue();
            serviceParams.put(paramEntry.getKey(), value.getValuesList().subList(0, value.getValuesCount()));
        }
        appRevisionInterface.setServiceParams(serviceParams);

        return appRevisionInterface;
    }
}
